<?php
namespace app\index\controller;

class Index
{
    public function __construct()
    {
        $this->appid = 'wxa5ad3d6956305b64';
        $this->appsecret = '1f6f610c845d039b13bc4767d37424fa';
        $this->callback = 'http://'.$_SERVER['HTTP_HOST'].url('index/index/callback');
    }

    public function index()
    {
        $state = 123;
        $callback =urlencode($this->callback);
        $url = "https://open.weixin.qq.com/connect/qrconnect?appid=".$this->appid."&redirect_uri=".$callback."&response_type=code&scope=snsapi_login&state=".$state."#wechat_redirect";
        return redirect($url);
    }

    public function callback()
    {
        $code = input('code');
        $acctoken = $this->getAccessToken($code);
        $usrinfo = $this->getUserInfo($acctoken['openid'], $acctoken['access_token']);
        var_dump($usrinfo);
    }

    public function getAccessToken($code)
    {
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code={$code}&grant_type=authorization_code";
        $array=(array)json_decode($this->http_curl($url));
        return $array;
    }

    public function getUserInfo($openid,$acctoken)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$acctoken."&openid=".$openid."&lang=zh_CN ";
        $array=(array)json_decode($this->http_curl($url));
        return $array;
    }

    public function http_curl($url)
    {
        $ch = curl_init($url) ;
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        $userInfo = curl_exec($ch) ;
        curl_close($ch);
        return $userInfo;
    }
}
